<template>
  <div class="Head" style="text-align: center;">
    <el-container class="background" style="height: 150px" ></el-container>
    <el-container style="height: 10vh">
      <el-header style="font-size: 50px;color: purple;letter-spacing: 40px">
        校爱同学管理平台
      </el-header>
    </el-container>
  </div>
  <div style="display: flex; justify-content: center; align-items: center;height: 10vh;
      border: 1px solid #ccc; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); margin: 50px 500px;padding: 100px 50px;">

  <el-form
      ref="loginForm"
      style="max-width: 600px"
      :model="data"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      @keydown.enter="Login">
  <!--model绑定表单数据,rules绑定验证规则-->
    <el-form-item label="账号:" prop="username">
      <el-input v-model="data.username" clearable/>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="data.password" type="password" clearable/>
    </el-form-item>
    <el-form-item style="margin: 30px 100px">
      <el-button type="primary" @click="Login" >
        登录
      </el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import {ElContainer, ElHeader} from 'element-plus'
import axios from "axios";
import router from '../router'
const data = reactive({
  username: '',
  password: ''
})
//绑定表单
const loginForm = ref(data)
const rules = {
  username: [{ required:true, message:'输账号啊', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        //验证账号位数和格式
        if (value.length === 10 && /^\d{10}$/.test(value)) {
          callback();
        } else {
          callback(new Error('你这账号有问题啊'));
        }
      },
      trigger: 'blur'
    }],
  password: [{ required:true, message:'输密码啊', trigger: 'blur' }]
}

const Login = async () => {
    // 进行表单验证，如果不通过则不发起请求
    const valid = await (loginForm.value).validate();
    if (!valid) {
      return;
    }
    //axios方法与后端一致
    const response = await axios.get(`/login/${data.username}/${data.password}`)
        .then(result=>{
          //数据验证与后端返回的数据一致
          if (result.data.message=="登录成功") {
            let information = JSON.stringify(result.data.data);
            sessionStorage.setItem('manager', information);
            // 使用路由进行页面跳转
            router.push('/user');
          } else {
            alert(result.data.message);
          }
        }).catch(error=>{
          alert('请求出现问题，请稍后再试'+error);
        })
};
</script>